import asyncio
import websockets
import json
from datetime import datetime

# 服务器消息计数器
server_counter = 0


async def handle_client(*args):
    """处理客户端连接和消息交换，兼容不同版本的websockets库"""
    global server_counter

    # 根据参数数量确定websocket对象（兼容不同版本）
    if len(args) == 1:
        websocket = args[0]
        path = "/"  # 默认路径
    else:
        websocket, path = args

    print(f"新客户端连接，路径: {path}")

    try:
        # 每1秒向客户端发送一次消息
        while True:
            # 构建JSON消息
            message = {
                "type": "server_message",
                "timestamp": datetime.utcnow().isoformat(),
                "counter": server_counter,
                "message": f"这是服务器发送的第 {server_counter} 条消息"
            }

            # 发送JSON字符串
            await websocket.send(json.dumps(message))
            print(f"服务器发送: {message}")

            server_counter += 1

            # 等待1秒
            await asyncio.sleep(1)

            # 同时监听客户端发送的消息
            try:
                # 使用超时，避免阻塞发送逻辑
                client_message = await asyncio.wait_for(websocket.recv(), timeout=0.1)
                print(f"收到客户端消息: {client_message}")
            except asyncio.TimeoutError:
                # 超时继续循环
                continue

    except websockets.exceptions.ConnectionClosed:
        print("客户端断开连接")
    finally:
        print("连接处理结束")


async def main():
    """启动WebSocket服务器"""
    async with websockets.serve(handle_client, "localhost", 8765):
        print("WebSocket服务器已启动，地址: ws://localhost:8765")
        await asyncio.Future()  # 保持服务器运行


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("服务器已停止")
